//获得元素
const logout = document.querySelector("#logout");
const textDanger = document.querySelector(".text-danger");
//退出按钮
logout.addEventListener("click", () => {
    //判断confirm返回值做出相应需求
    if (confirm(`确定要退出吗`)) {
        localStorage.removeItem("token87888788");
        location.href = "login.html";
    }
})

//获得数据并拼接
async function getStudents() {
    const reslut = await axios({
        url: "/students",
    });
    //学员数量
    document.querySelector(".total").innerText = reslut.data.data.length;
    console.log(reslut.data.data);
    document.querySelector("tbody").innerHTML = reslut.data.data.map((item) => {
        const { age, city, gender, id, province, name, group, hope_salary, salary, area
        } = item;
        return `
        <tr>
        <td>${name}</td>
        <td>${age}</td>
        <td>${gender === 0 ? "男" : "女"}</td>
        <td>第${group}组</td>
        <td>${hope_salary}</td>
        <td>${salary}</td>
        <td>${province}${city}${area}</td>
        <td><a href="javascript:;" class="text-success mr-3"><i data-id="${id
            }" class="bi bi-pen"></i></a>
                              <a  href="javascript:;" class="text-danger"><i data-id="${id
            }" class="bi bi-trash"></i></a></td>
      </tr>
        `
    }).join("");

}
getStudents();

//修改和删除功能
document.querySelector("tbody").addEventListener("click", async (e) => {
    if (e.target.tagName == "I") {
        //判断是否是删除按钮
        if (e.target.classList.contains("bi-trash")) {
            //判断是否删除
            if (confirm(`确定要删除吗`)) {
                await axios({
                    url: `/students/${e.target.dataset.id}`,
                    method: "delete",
                })
                //重新渲染
                getStudents()
            }
        }

        //编辑部分
        if (e.target.classList.contains("bi-pen")) {

            const res = await axios({
                url: `/students/${e.target.dataset.id}`
            })
            console.log(res.data.data);
            const ress = res.data.data;
            await renderProvince(ress.province)
            await renderCity(ress.city);
            await renderArea(ress.area);
            let obj = {};
            for (const key in ress) {
                const inputValue = document.querySelector(`[name=${key}]`);
                //console.log('inputValue:', inputValue)
                if (inputValue) {
                    obj[key] = `${ress[key]}`
                }
            }
            for (const key in obj) {
                if (key == "gender") {
                    const genders = document.querySelectorAll('[name=gender]')
                    genders[ress[key]].checked = true;
                }
                document.querySelector(`[name=${key}]`).value = obj[key];
            }
            console.log(obj);
            modal.show();
            document.querySelector(".modal-title").innerHTML = `<h5 class="modal-title">编辑学员</h5>`;
            const id = e.target.dataset.id;
            document.querySelector("#submit").dataset.id = id

        }
    }
})

//城市省份的获取


//省份函数
async function renderProvince(province = '') {
    // 省
    const res = await axios({
        url: '/api/province'
    })
    // console.log('res:', res)
    document.querySelector('[name=province]').innerHTML = res.data.data
        .map(v => {
            return `<option value="${v}">${v}</option>`
        })
        .join('')
    // 如果传入了 省,选中对应的省
    province !== '' &&
        (document.querySelector('[name=province]').value = province)
}

// 获取市数据
async function renderCity(city = '') {
    // 默认 北京 被选中
    const pname = document.querySelector('[name=province]').value
    // console.log('pname:', pname)
    // 市
    const res = await axios({
        url: '/api/city',
        params: {
            pname
        }
    })
    document.querySelector('[name=city]').innerHTML = res.data.data
        .map(v => `<option value="${v}">${v}</option>`)
        .join('')

    // 如果传入了 城市,选中对应的城市
    city !== '' && (document.querySelector('[name=city]').value = city)
}
// 获取区数据
async function renderArea(area = '') {
    // 获取 省 获取 市
    const pname = document.querySelector('[name=province]').value
    const cname = document.querySelector('[name=city]').value
    // 区
    const res = await axios({
        url: '/api/area',
        params: {
            pname,
            cname
        }
    })
    // console.log('res:', res)
    document.querySelector('[name=area]').innerHTML = res.data.data
        .map(v => `<option value="${v}">${v}</option>`)
        .join('')
    // 如果传入了 area 选中对应的area
    // select 设置了value之后,选中对应的option
    area !== '' && (document.querySelector('[name=area]').value = area)
}

//加载省市区
async function renderSelect() {
    await renderProvince()
    await renderCity()
    await renderArea()
};

renderSelect()

//省市区联动效果
document.querySelector('[name=province]').onchange = async function () {
    // console.log('pro-change')
    // 重新获取 市
    await renderCity()
    // 重新获取 区
    await renderArea()
}
document.querySelector('[name=city]').onchange = async function () {
    // 重新获取 区
    await renderArea()
}



//增加部分
document.querySelector("#openModal").addEventListener("click", async () => {
    document.querySelector(".modal-title").innerHTML = `<h5 class="modal-title">添加学员</h5>`
    modal.show();
    document.querySelector('#form').reset();

});
document.querySelector("#submit").addEventListener("click", async function (e) {

    if (document.querySelector(".modal-title").innerText === "添加学员") {
        const data = serialize(form, { hash: true }); // 返回对象
        console.log(data);
        data.age = +data.age
        data.gender = +data.gender
        data.salary = +data.salary
        data.hope_salary = +data.hope_salary
        data.group = +data.group
        const reslut = await axios({
            url: "/students",
            method: "post",
            data,
        });
        getStudents();
        modal.hide();
    } else {
        const data = serialize(form, { hash: true }); // 返回对象
        const id = e.target.dataset.id
        console.log(id);
        data.age = +data.age
        data.gender = +data.gender
        data.salary = +data.salary
        data.hope_salary = +data.hope_salary
        data.group = +data.group
        const reslut = await axios({
            url: `/students/${e.target.dataset.id}`,
            method: "put",
            data,
        })
        getStudents();
        modal.hide();
    }


});


